# === load relevant libraries
library(data.table)
library(ggplot2)
library(DescTools)
library(plm)
library(lfe)
library(dplyr)
library(sandwich)

rm(list = ls())

# style data
data = readRDS('input_data/morningstar_style_data.RDS')[, list(yyyymm, category, flow, expSum_1)]

# first rank by realized flow
data = data[order(yyyymm, flow)]
for (this in unique(data[, yyyymm])){
  data[yyyymm == this, rank_flow := 1:9]
}

# then rank by lagged exponential sum of ratings
data = data[order(yyyymm, expSum_1)]
for (this in unique(data[, yyyymm])){
  data[yyyymm == this, rank_rating := 1:9]
}
rm(this)

# summarize
data[, period := ifelse(yyyymm > 200206, 2, 1)]
out = data[, list(type = ' Ranked by flow (maximum dispersion)', flow = mean(flow)), list(period, rank = rank_rating)]
out = rbind(out, data[, list(type = 'Ranked by ExpSum(dRating)', flow = mean(flow)), list(period, rank = rank_flow)])
data = copy(out); rm(out)

# demean by period
data = merge(data, data[, list(m = mean(flow)), list(period, type)], by = c('period','type'))
data[, flow := flow - m]
data[, m := NULL]
yy = c(-.02, .02)

# plot Figure A5 (a): before june 2002
ggplot(data[period == 1], aes(x = rank, y = flow, fill = type)) + geom_bar(stat = 'identity', position = 'dodge') + 
  coord_cartesian(ylim = yy) + theme_classic() + theme(legend.title = element_blank(), legend.position = c(.4, .8)) + 
  labs(x = 'Ranked styles', y = 'Monthly flow (demeaned)') + scale_y_continuous(labels = scales::percent_format(accuracy = .1)) + 
  scale_x_discrete(limits = factor(1:9), labels = c('Bot',2:8,'Top'))

# plot Figure A5 (b): after june 2002
ggplot(data[period == 2], aes(x = rank, y = flow, fill = type)) + geom_bar(stat = 'identity', position = 'dodge') + 
  coord_cartesian(ylim = yy) + theme_classic() + theme(legend.title = element_blank(), legend.position = c(.4, .8)) + 
  labs(x = 'Ranked styles', y = 'Monthly flow (demeaned)') + scale_y_continuous(labels = scales::percent_format(accuracy = .1)) + 
  scale_x_discrete(limits = factor(1:9), labels = c('Bot',2:8,'Top'))
